import json
from flask import (Blueprint, request, session)
from flaskr import  Utils
bp = Blueprint('delField',__name__, url_prefix='/delField')

from flaskr.server.SheetsServer import *
@bp.route('', methods = ['POST'])
def delField():
    sheet_name = request.json.get('sheetName')
    field_name = request.json.get('fieldName')

    has_change = False

    # if('sheets' in session.keys()):
    #     sheets = session['sheets']

    # for sheet in sheets:
    #     if (sheet['showName'] == sheet_name):
    #         json_ = sheet['json']
    #
    #         df = Utils.jsonToDataFrame(json_)
    #         df = df.drop(field_name, axis=1)
    #         json_ = Utils.dataFrameToJson(df)
    #
    #         sheet['columns'] = Utils.getColumns(df) #重新获取所有字段
    #         sheet['json'] = json_
    #         sheet['table'] = Utils.dataFrameToHtml(df)
    #         sheet['types'] = Utils.getTypes(df)
    #         session['sheets'] = sheets
    #
    #         has_change = True
    #
    #         break
    sheet = get_sheet(sheet_name)
    if sheet:
        df = get_dataframe(sheet_name)

        df = df.drop(field_name, axis=1)

        if has_pkl(sheet_name):
            setPkl(df, sheet['md5'])
            df = df.head(200)
        json_ = Utils.dataFrameToJson(df)

        sheet['columns'] = Utils.getColumns(df) #重新获取所有字段
        sheet['json'] = json_
        sheet['table'] = Utils.dataFrameToHtml(df)
        sheet['types'] = Utils.getTypes(df)

        set_sheet(sheet_name, sheet)
        has_change = True

    if has_change:
        return {
            'code': 200,
            'msg': '删除成功',
            'data': sheet
        }

    else:
        return {
            'code': 500,
            'msg': '删除失败'
        }